import React, { useState, useEffect } from 'react';
import { groupAPI, userAPI } from '../../services/api';
import LoadingSpinner from '../../components/common/LoadingSpinner';
import Button from '../../components/common/Button';
import { FiShuffle, FiSave, FiRefreshCw, FiUser, FiUsers } from 'react-icons/fi';

const GroupManagement = () => {
  const [users, setUsers] = useState([]);
  const [groups, setGroups] = useState([]);
  const [groupCount, setGroupCount] = useState(5);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await userAPI.getUsers({ limit: 1000 });
      
      if (response.data.success) {
        setUsers(response.data.data.users);
      }
    } catch (err) {
      setError('获取用户列表失败');
      console.error('获取用户列表错误:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleRandomGrouping = async () => {
    if (window.confirm('确定要重新随机分组吗？这将覆盖当前的分组结果。')) {
      setSaving(true);
      try {
        const userIds = users.map(user => user._id);
        
        const response = await groupAPI.randomGrouping({
          activityId: 'temp-activity-id', // 这里应该使用实际的活动ID
          userIds,
          groupCount
        });
        
        if (response.data.success) {
          setGroups(response.data.data.groups);
        }
      } catch (err) {
        alert('随机分组失败');
        console.error('随机分组错误:', err);
      } finally {
        setSaving(false);
      }
    }
  };

  const handleSaveGrouping = async () => {
    setSaving(true);
    try {
      // 这里应该保存分组结果到服务器
      alert('分组结果已保存');
    } catch (err) {
      alert('保存分组结果失败');
      console.error('保存分组结果错误:', err);
    } finally {
      setSaving(false);
    }
  };

  const handleResetGrouping = () => {
    if (window.confirm('确定要重置分组吗？这将清除所有分组结果。')) {
      setGroups([]);
    }
  };

  const handleDragStart = (e, userId) => {
    e.dataTransfer.setData('userId', userId);
  };

  const handleDragOver = (e) => {
    e.preventDefault();
  };

  const handleDrop = (e, groupId) => {
    e.preventDefault();
    const userId = e.dataTransfer.getData('userId');
    
    // 更新分组成员
    setGroups(prevGroups => 
      prevGroups.map(group => {
        if (group._id === groupId) {
          // 添加用户到目标组
          return {
            ...group,
            members: [...group.members, users.find(u => u._id === userId)]
          };
        } else {
          // 从其他组中移除用户
          return {
            ...group,
            members: group.members.filter(member => member._id !== userId)
          };
        }
      })
    );
  };

  const getUserStatusBadge = (status) => {
    const statusClasses = {
      online: 'bg-green-100 text-green-800',
      offline: 'bg-gray-100 text-gray-800'
    };
    
    const statusText = {
      online: '在线',
      offline: '离线'
    };
    
    return (
      <span className={`ml-2 px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClasses[status]}`}>
        {statusText[status]}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <LoadingSpinner />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border-l-4 border-red-400 p-4">
        <div className="flex">
          <div className="flex-shrink-0">
            <svg className="h-5 w-5 text-red-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
            </svg>
          </div>
          <div className="ml-3">
            <p className="text-sm text-red-700">
              {error}
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="py-6">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 md:px-8">
        <div className="flex justify-between items-center">
          <h1 className="text-2xl font-semibold text-gray-900">分组管理</h1>
          <div className="flex space-x-3">
            <div className="flex items-center">
              <label htmlFor="groupCount" className="mr-2 text-sm font-medium text-gray-700">
                组数:
              </label>
              <select
                id="groupCount"
                className="block w-20 pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"
                value={groupCount}
                onChange={(e) => setGroupCount(parseInt(e.target.value))}
              >
                {[...Array(20)].map((_, i) => (
                  <option key={i + 1} value={i + 1}>{i + 1}</option>
                ))}
              </select>
            </div>
            <Button 
              variant="primary" 
              onClick={handleRandomGrouping}
              loading={saving}
            >
              <FiShuffle className="mr-2" /> 随机分组
            </Button>
            <Button 
              variant="success" 
              onClick={handleSaveGrouping}
              loading={saving}
            >
              <FiSave className="mr-2" /> 保存分组
            </Button>
            <Button 
              variant="secondary" 
              onClick={handleResetGrouping}
            >
              <FiRefreshCw className="mr-2" /> 重置
            </Button>
          </div>
        </div>
      </div>
      
      <div className="max-w-7xl mx-auto px-4 sm:px-6 md:px-8">
        <div className="mt-6 grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* 未分组用户 */}
          <div className="lg:col-span-1">
            <div className="bg-white shadow overflow-hidden sm:rounded-lg">
              <div className="px-4 py-5 sm:px-6">
                <h3 className="text-lg leading-6 font-medium text-gray-900">
                  未分组用户
                </h3>
                <p className="mt-1 text-sm text-gray-500">
                  共 {users.length} 人
                </p>
              </div>
              <div 
                className="border-t border-gray-200 p-4 min-h-96"
                onDragOver={handleDragOver}
              >
                <div className="space-y-3">
                  {users.map((user) => (
                    <div
                      key={user._id}
                      draggable
                      onDragStart={(e) => handleDragStart(e, user._id)}
                      className="bg-gray-50 rounded-md p-3 cursor-move hover:bg-gray-100 transition-colors"
                    >
                      <div className="flex items-center">
                        <div className="flex-shrink-0 h-8 w-8 rounded-full bg-gray-200 flex items-center justify-center">
                          <FiUser className="h-4 w-4 text-gray-500" />
                        </div>
                        <div className="ml-3">
                          <p className="text-sm font-medium text-gray-900">{user.name}</p>
                          <p className="text-xs text-gray-500">{user.username}</p>
                        </div>
                        {getUserStatusBadge(user.status)}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
          
          {/* 分组区域 */}
          <div className="lg:col-span-3">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {Array.from({ length: groupCount }, (_, i) => {
                const group = groups[i] || { _id: `group-${i}`, name: `第${i + 1}组`, members: [] };
                return (
                  <div 
                    key={group._id}
                    className="bg-white shadow overflow-hidden sm:rounded-lg"
                    onDragOver={handleDragOver}
                    onDrop={(e) => handleDrop(e, group._id)}
                  >
                    <div className="px-4 py-5 sm:px-6">
                      <h3 className="text-lg leading-6 font-medium text-gray-900">
                        {group.name}
                      </h3>
                      <p className="mt-1 text-sm text-gray-500">
                        {group.members.length} 人
                      </p>
                    </div>
                    <div className="border-t border-gray-200 p-4 min-h-96">
                      <div className="space-y-3">
                        {group.members.map((member) => (
                          <div
                            key={member._id}
                            className="bg-blue-50 rounded-md p-3"
                          >
                            <div className="flex items-center">
                              <div className="flex-shrink-0 h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center">
                                <FiUser className="h-4 w-4 text-blue-600" />
                              </div>
                              <div className="ml-3">
                                <p className="text-sm font-medium text-gray-900">{member.name}</p>
                                <p className="text-xs text-gray-500">{member.username}</p>
                              </div>
                              {getUserStatusBadge(member.status)}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default GroupManagement;